<?php
/**
 * Created by PhpStorm.
 * User: woody
 * Date: 17-2-16
 * Time: 下午10:46
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\AdminController;
use Illuminate\Http\Request;

use Validator;

use App\Models\Stores;
use Illuminate\Database\Eloquent\Model;

class StoresController extends AdminController {

    private $_length = 20;

    public function __construct()
    {
        parent::__construct();
        $this->_response['_active']['_model']       = 'stores';
        $this->_response['_active']['_action']      = '';
        $this->_response['_title']                  = '小一农货-门店管理';
    }

    public function getList(Request $request){
        $page = 1;
        $search = [];
        $param = '';
        $this->_response['_active']['_action']      = 'list';
        
        if($request->has('page')) {
            $page = $request->get('page');
        }
        $offset = ($page - 1) * $this->_length;
        
        $storeModel = new Stores();
        $this->_response['stores'] = $storeModel->getStoresList($search, $offset, $this->_length);
        $this->_response['stores']['pageData']['page'] = $page;
        $this->_response['stores']['pageData']['pageHtml'] = self::getPageHtml($page , $this->_response['stores']['pageData']['lastPage'] , '/admin/stores?' . $param);

        return view('admin.stores.list' , $this->_response);
    }

    public function add(Request $request){
        $this->_response['_active']['_action']    = 'add';
        return view('admin.stores.add' , $this->_response);
    }
    
    public function doAdd(Request $request){
        $validation = Validator::make($request->all(), [
            'name'                  => 'required',
            'address'               => 'required',
            'mobile'                => 'required',
            'contact'               => 'required',
            'i_d_card'              => 'required',
            'business_license'      => 'required',
            'lat'                   => 'required',
            'lng'                   => 'required',
            'adcode'                => 'required',
            'password'                => 'required',
        ] , [
            'name.required'             => '必须填写店铺名称',
            'address.required'          => '必须填写店铺地址',
            'mobile.required'           => '必须填写联系方式',
            'contact.required'          => '必须填写联系人',
            'i_d_card.required'         => '必须填写身份证',
            'business_license.required' => '必须上传营业执照',
            'lat.required'              => '获取位置失败',
            'lng.required'              => '获取位置失败',
            'adcode.required'           => '获取位置失败',
            'password.required'           => '必须填写密码',
        ]);
        if($validation->fails()) {
            $error = $validation->errors()->all();
            return response()->json(['code' => -1, 'msg' => $error[0]]);
        }
        
        $saveData = $request->all();

        $saveData['salt'] = getSalt(8);
        $saveData['password'] = encrypt_sha_md5($saveData['password'] , $saveData['salt']);

        $saveData['address'] = $saveData['pcd'] . $saveData['address'];
        unset($saveData['pcd']);
        
        $storeModel = new Stores();
        $storeId = $storeModel->saveStore($saveData);
        if($storeId) {

            $amapAddress = array(
                "_name"		=> $saveData['name'],
                "_location" => "{$saveData['lng']},{$saveData['lat']}",
                "_address"	=> $saveData['address'],
                "store_id"	=> $storeId
            );

            $amapId = $this->mapMark($amapAddress);

            if($amapId){
                \Log::notice("添加云图成功");
            }else{
                \Log::notice("添加云图失败");
            }

            Stores::where('id' , $storeId)->update(['amap_id' => $amapId]);

            return response()->json(['code' => 0 , 'msg' => '添加成功']);
        }else {
            return response()->json(['code' => -1 , 'msg' => '添加失败,请稍后重试']);
        }
        
    }
    
    public function getStores($sid) {
        $storeModel = new Stores();
        $stores = $storeModel->getStoresList(['ids'=> [$sid], 0, 1]);
        
        if(count($stores['list']) == 1) {
            $this->_response['info'] = $stores['list'][0];
        }else {
            $this->_response['info'] = [];
        }
        return view('admin.stores.edit', $this->_response);
    }
    
    public function update(Request $request){
        $validation = Validator::make($request->all(), [
            'id'                    => 'required',
            'name'                  => 'required',
            'address'               => 'required',
            'mobile'                => 'required',
            'contact'               => 'required',
            'i_d_card'              => 'required',
            'business_license'      => 'required',
            'lat'                   => 'required',
            'lng'                   => 'required',
            'adcode'                => 'required',
        ] , [
            'id.required'               => '没有要修改的店铺',
            'name.required'             => '必须填写店铺名称',
            'address.required'          => '必须填写店铺地址',
            'mobile.required'           => '必须填写联系方式',
            'contact.required'          => '必须填写联系人',
            'i_d_card.required'         => '必须填写身份证',
            'business_license.required' => '必须上传营业执照',
            'lat.required'              => '获取位置失败',
            'lng.required'              => '获取位置失败',
            'adcode.required'           => '获取位置失败',
        ]);
        
        if($validation->fails()){
            $error = $validation->errors()->all();
            return response()->json(['code' => -1 , 'msg' => $error[0]]);
        }
        
        $saveData = $request->all();
        
        $sId = $saveData['id'];
        unset($saveData['id']);

        if($request->has('password')) {
            $saveData['salt'] = getSalt(8);
            $saveData['password'] = encrypt_sha_md5($saveData['password'], $saveData['salt']);
        }

        if($saveData['password'] == null){
            unset($saveData['password']);
        }

        $saveData['address'] = $saveData['pcd'] . $saveData['address'];
        unset($saveData['pcd']);
        
        $saveData['updated_at'] = date('Y-m-d H:i:s' , $_SERVER['REQUEST_TIME']);
        
        $storeModel = new Stores();
        if($storeModel->updateStore($sId , $saveData)){

            $storeInfo = Stores::where('id' , $sId)->first();

            $amapAddress = array(
                "_id"       => $storeInfo->amap_id,
                "_name"		=> $saveData['name'],
                "_location" => "{$saveData['lng']},{$saveData['lat']}",
                "_address"	=> $saveData['address'],
                "store_id"  => $sId
            );

            if($this->mapMark($amapAddress)){
                \Log::notice("更改云图成功");
            }else{
                \Log::notice("更改云图失败");
            }

            return response()->json(['code' => 0 , 'msg' => '添加成功']);
        }else{
            return response()->json(['code' => -1 , 'msg' => '添加失败,请稍后重试']);
        }
    }
    
    public function delete($sId){
        if(Stores::where('id', $sId)->update(['deleted_at' => date('Y-m-d H:i:s' , $_SERVER['REQUEST_TIME'])]) ){
            return response()->json(['code' => 0 , 'msg' => '删除成功']);  
        }else{
            return response()->json(['code' => -1 , 'msg' => '删除失败,请稍后重试']);
        }
    }
    
    
}